package main

import (
	"context"
	"github.com/olivere/elastic/v7"
	"gopkg.in/yaml.v3"
	"io/ioutil"
	"log"
	"os"
)

var cfg = struct {
	LogLevel   string   `yaml:"logLevel"`
	ElasticDSN string   `yaml:"elasticDSN"`
	SchemaPath string   `yaml:"schemaPath"`
	Indices    []string `yaml:"indices"`
}{}
var client *elastic.Client

func init() {
	b, err := ioutil.ReadFile("config.yaml")
	if err != nil {
		panic(err)
	}
	err = yaml.Unmarshal(b, &cfg)
	if err != nil {
		log.Fatal("load config:", err)
	}
	client, err = elastic.NewSimpleClient(elastic.SetURL(cfg.ElasticDSN))
	if err != nil {
		log.Fatal("elastic:", err)
	}
}

func main() {
	f, err := os.Open(cfg.SchemaPath)
	if err != nil {
		log.Fatal("open schema:", err)
	}
	defer func() {
		_ = f.Close()
	}()
	dec := yaml.NewDecoder(f)
	for i, name := range cfg.Indices {
		var schema map[string]interface{}
		err = dec.Decode(&schema)
		if err != nil {
			log.Fatalf("unmarshal %s(%d): %v", name, i, err)
		}
		ok, err := client.IndexExists(name).Do(context.Background())
		if err != nil {
			log.Fatalf("check index %s(%d) exists: %v", name, i, err)
		}
		if ok {
			log.Printf("deleting index %s(%d)", name, i)
			_, err := client.DeleteIndex(name).Do(context.Background())
			if err != nil {
				log.Fatalf("delete index %s(%d): %v", err)
			}
		}
		log.Printf("creating index %s(%d)", name, i)
		putSettingsResult, err := client.CreateIndex(name).BodyJson(schema).Do(context.Background())
		if err != nil {
			log.Fatalf("create index %s: %v", name, err)
		} else {
			log.Printf("created index %s", putSettingsResult.Index)
		}
	}
}
